package com.fary.filter;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.fary.web.request.CustomHttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@WebFilter
@Slf4j
public class LogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 防止流读取一次后就没有了, 所以需要将流继续写出去
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestContentType = httpServletRequest.getHeader(HttpHeaders.CONTENT_TYPE);
        if (StrUtil.startWithAny(requestContentType, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE)) {
            servletRequest = new CustomHttpServletRequestWrapper(httpServletRequest);
            printRequest(servletRequest);
        }
        filterChain.doFilter(servletRequest, servletResponse);
        if (StrUtil.startWithAny(requestContentType, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE)) {
            log.info("请求结束 url === {}", ((HttpServletRequest) servletRequest).getRequestURI());
        }
    }

    private void printRequest(ServletRequest servletRequest) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        log.info("请求开始 url === {}", request.getRequestURI());
        log.info("请求开始 参数 === {}", getRequestBody(request));
    }

    public String getRequestBody(HttpServletRequest request) {
        int contentLength = request.getContentLength();
        if (contentLength <= 0) {
            return "";
        }
        try {
            return IoUtil.read(request.getReader());
        } catch (IOException e) {
            log.error("获取请求体失败", e);
            return "";
        }
    }

    @Override
    public void destroy() {
    }

}
